<template>
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="!editid?`新增资产`:`修改资产`" :autoBack="true" leftIconColor="$uni-text-color"
    :bgColor="'rgba(0,0,0,0)'" :titleStyle="{ color: '#fff', fontSize: '32rpx' }">

    <view class="container"
      :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`, paddingTop: (safeAreaInsets?.top + 44) + 'px' }">

      <!-- 表单盒子 -->
      <view class="form_box area">
        <scroll-view scroll-y :enable-back-to-top="true" class="comprehensive">
          <!-- 表单结构 -->
          <uni-forms ref="relRef" v-model="state.formData" :rules="state.rules" validateTrigger="bind" labelWidth="120">
            <uni-forms-item name="classify" label="分类：" required>
              <uni-easyinput @tap="chooseClassify"  :disabled="true"  placeholder="请输入分类" v-model="state.formData.classify" :inputBorder="false" >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="title" label="名称：" required>
              <uni-easyinput placeholder="请输入名称" v-model="state.formData.title" :inputBorder="false" >
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="serialNumber" label="编号：" required>
              <uni-easyinput placeholder="请输入编号"  v-model="state.formData.serialNumber" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="brand" label="品牌：" required>
              <uni-easyinput placeholder="请输入品牌" v-model="state.formData.brand" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="model" label="型号：" required>
              <uni-easyinput placeholder="请输入型号" v-model="state.formData.model" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="number" label="规格数量：" required>
              <uni-easyinput placeholder="请输入规格数量" type="number" v-model="state.formData.number" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="price" label="资产价值：" >
              <uni-easyinput placeholder="请输入价值" type="number" v-model="state.formData.price" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="date" label="采购日期：" >
              <view class="dates"  @tap="choosePurchaseDate(1)">
                <image :src="`${baseUrl}/uploads/uniapp_image/staff/class_icon01.png`"  mode="scaleToFill"/>
                <view :class="state.formData.purchase_date?'gray':'placeholder'">{{ state.formData.purchase_date ?state.formData.purchase_date:'请选择采购日期' }}</view>
              </view>
            </uni-forms-item>
            <uni-forms-item name="date" label="报废日期：" >
              <view class="dates"  @tap="choosePurchaseDate(2)">
                <image :src="`${baseUrl}/uploads/uniapp_image/staff/class_icon01.png`"  mode="scaleToFill"/>
                <view :class="state.formData.scrap_date?'gray':'placeholder'">{{ state.formData.scrap_date ?state.formData.scrap_date:'请选择报废日期' }}</view>
              </view>
            </uni-forms-item>
            <uni-forms-item name="keeper" label="保管人：" >
              <uni-easyinput placeholder="请输入保管人" v-model="state.formData.keeper" :inputBorder="false">
              </uni-easyinput>
            </uni-forms-item>
            <uni-forms-item name="remark" label="备注：">
              <view class="flex-vertical">
                <uni-easyinput type="textarea" v-model="state.formData.remark" placeholder="请输入内容"></uni-easyinput>
              </view>
            </uni-forms-item>
            <view class="cards">
							<view class="title">图片:</view>
              <u-upload :fileList="state.fileList1" @afterRead="imageUpload" @delete="deletePic" name="4" multiple
              :maxCount="4">
            </u-upload>
						</view>
          </uni-forms>

        </scroll-view>
      </view>

    </view>

  </s-layout>

  <!-- 底部提交按钮 -->
  <view >
    <s-button @netWork="submitForm" :text="!editid?text:edittext"></s-button>
  </view>

 <!-- 分类 -->
    <s-popup-list @selectedData="classifySwitchTitle" 
    :arrayList="classifyDataList"
    ref="popupclassifyListRef" 
    :popupTitle="'选择分类'" 
    :listingName="'列表名称'" 
    :searchBoxIsShow="false"
    :isPage="false"
    :showGoLink="'#'"></s-popup-list>
    <!-- 采购日期 -->
      <!-- 日期范围 -->
      <up-calendar :monthNum="12" :closeOnClickOverlay="true" :show="PurchaseDateShow" :mode="mode" @confirm="PurchaseConfirm" @close="PurchaseDateClose"></up-calendar>
</template>

<script setup>
import sheep from '@/sheep';
import { ref, reactive, unref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { baseUrl } from "@/sheep/config";
import { classify, title, serialNumber, brand, model ,number} from '@/sheep/validate/form';
const { safeAreaInsets } = uni.getSystemInfoSync();
const text = ref("提交");
const edittext =  ref('修改')
const state = reactive({
  fileList1: [],
  fordataView:'',
  formData: {
    classify: '',//分类
    title: '',
    serialNumber: '',
    brand: '',
    model: '',
    number:'',
    price:'',
    purchase_date:'',
    scrap_date:'',
    keeper:'',
    remark:'',
    uploadimg:''

  },
  rules: {
    classify,
    title,
    serialNumber,
    brand,
    model,
    number,
  },
});
const  editid = ref('')
onLoad((options)=>{
  editid.value = options.ids
  classifyList()
  if(options.ids){
    getAssteView()
  }
})
//详情接口
const getAssteView = async()=>{
  let parpam={
    ids:editid.value 
  }
  const res= await sheep.$api.asset.getAssteView(parpam);
  state.formData = res?.data
  state.formData.classify = res?.data.category.title
  state.formData.serialNumber = res?.data.code
  state.formData.number = res?.data.size
  classify_id.value = res?.data.category.id
  const item= res?.data.images.split(',')
  if(res.data.images){
    item.forEach((a,index)=>{
      state.fileList1?.push({
        url:`${baseUrl}`+a
      })
      postData.value.push(a)
    }) 
  }
  
}
//------------------ 分类开始-----------------------
const popupclassifyListRef =  ref()
const classify_id = ref()
const classifyDataList = ref([])
const classifyList = async()=>{
  const res= await sheep.$api.asset.getAssetIndexList();
  classifyDataList.value = res?.data
}
const chooseClassify = ()=>{

  popupclassifyListRef.value.open()

}
// 子组件触发的方法将项目title 
const classifySwitchTitle = (data) => {
  state.formData.classify = data.title
  classify_id.value = data.id
}

//------------------ 分类结束-----------------------
//采购日期
const PurchaseDateShow =  ref(false)
const dateid= ref()
const choosePurchaseDate = (e)=>{
  dateid.value = e
  PurchaseDateShow.value = true
}
const PurchaseDateClose = ()=>{
  PurchaseDateShow.value = false
}
const PurchaseConfirm = (e)=>{
  if( dateid.value == 1){
    state.formData.purchase_date = `${e}`
  }
  if(dateid.value == 2){
    state.formData.scrap_date = `${e}`
  }
  PurchaseDateShow.value = false

}
//上传图片结束-----------------
const relRef = ref();
//提交和修改
const submitForm =  async() => {
  const validate = await unref(relRef)
    .validate()
    .catch((error) => {
    });
  if (!validate) return;
  if(!editid.value){

    state.formData.uploadimg = postData.value.join(',')

    let parpam ={
    category_id:classify_id.value,
    title:state.formData.title,
    code:state.formData.serialNumber,
    brand:state.formData.brand,
    model:state.formData.model,
    size:state.formData.number,
    price:state.formData.price,
    purchase_date:state.formData.purchase_date,
    scrap_date:state.formData.scrap_date,
    keeper:state.formData.keeper,
    remark:state.formData.remark,
    images:state.formData.uploadimg,
  }
  sheep.$api.asset.postAssteAdd(parpam).then((res) => {
    if(res.code == 1){
      sheep.$helper.toast(res.msg);
    setTimeout(function() {
     sheep.$router.back(true)
      }, 500);
        
      }else{
        sheep.$helper.toast(res.msg);
      
      }
		});
  }else{
    state.formData.uploadimg = postData.value.join(',')
    let parpam ={
    ids:editid.value, 
    category_id:classify_id.value,
    title:state.formData.title,
    code:state.formData.serialNumber,
    brand:state.formData.brand,
    model:state.formData.model,
    size:state.formData.number,
    price:state.formData.price,
    purchase_date:state.formData.purchase_date,
    scrap_date:state.formData.scrap_date,
    keeper:state.formData.keeper,
    remark:state.formData.remark,
    images:state.formData.uploadimg,
  }
  sheep.$api.asset.postAssteEdit(parpam).then((res) => {
    if(res.code == 1){
      sheep.$helper.toast(res.msg);
    setTimeout(function() {
     sheep.$router.back(true)
      }, 500);
        
      }else{
        sheep.$helper.toast(res.msg);
      }
		});
  }

};
// 删除图片
const deletePic = (event) => {
  state.fileList1.splice(event.index, 1);
  postData.value.splice(event.index, 1);
};

// 新增图片
const imageUpload = async (event) => {
  let lists = [].concat(event.file);
  let fileListLen = state.fileList1.length;
  lists.map((item) => {
    state.fileList1.push({
      ...item,
      status: 'uploading',
      message: '上传中',
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const url = await uploadFilePromise(lists[i].url);
    let item = state.fileList1[fileListLen];
    state.fileList1.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: sheep.$url.cdn(url),
    });
    fileListLen++;
  }
};
const postData = ref([])
async function uploadFilePromise(tempUrl) {
  let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
  postData.value.push(url);
  return url;

};



</script>

<style scoped lang="scss">
@import '../compentns/public.scss';

:deep(.uni-forms) {
  .uni-forms-item.is-direction-left {
    &:nth-last-child(2) {
      .uni-forms-item__label {
        background: $uni-bg-color;
      }

      flex-direction: column !important;
      height: auto;
    }

  }

  .uni-forms-item.is-direction-left {
    &:last-child {
      .uni-forms-item__label {
        background: $uni-bg-color;
      }

      flex-direction: column !important;
      height: auto;
    }

  }
}

:deep(.is-disabled) {
  .uni-easyinput__placeholder-class {
    color: #666 !important;
  }
}
:deep(.is-textarea) {
  .uni-easyinput__placeholder-class {
    color: #999 !important;
  }
  .uni-easyinput__content-textarea{
    color: #353434 !important;
  }
}
:deep(.is-disabled){
  .uni-easyinput__placeholder-class{
    color: $uni-color-primary !important;
  }   

}
.comprehensive{
  width: 100%;
  margin: 0;
}
//日期
.dates{
  width: 278rpx;
  text-align: right;
  border: #1241E2 1rpx solid;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 16rpx;
  height: 64rpx;
  margin: 15rpx 0 0 200rpx;
  image{
    width: 28rpx;
    height: 26rpx;
    margin-right: 10rpx;
  }
  .placeholder{
    color: $uni-color-primary;
    font-weight: 500;
   font-size:$uni-font-size-26;
  }
  .gray{
    color: #999;
    font-weight: 500;
   font-size:$uni-font-size-26;
  }
}
//图片
.cards {
  width: 100%;
  border-radius: 16rpx;
  background-color: #FFFFFF;
  // box-shadow: 0 4rpx 8rpx 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 120rpx;
  padding-bottom: 20rpx;
    :deep(.u-upload) {
      margin: 30rpx 0;
      width: 100% !important;
      background: #fff !important;
      .u-upload__wrap{
        flex-direction: row !important;
        flex-wrap: wrap !important;
        justify-content: flex-start !important;
      }
      
// .uploadimg {
//   width: 60rpx;
//   height: 48rpx;
// }
}

// .uploadimg {
//   width: 60rpx;
//   height: 48rpx;
// }
}
</style>